const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user.js');
const article = require('../db/article');
const album = require('../db/album');
const comment = require('../db/comment');
const Msg = require('../db/msg');
const multer = require('multer');
const fs = require('fs');
const validator = require('validator');
const wc = require('sensitive-word-filter');
const Routes = require('../db/routes');
//IP地址
let os = require('os');
let getIPAddress = function () {
    let ifaces = os.networkInterfaces();
    let ip = '';
    for (let dev in ifaces) {
        ifaces[dev].forEach(function (details) {
            if (ip === '' && details.family === 'IPv4' && !details.internal) {
                ip = details.address;
                return;
            }
        });
    }
    return ip || "127.0.0.1";
};

let MD = require('../util').MD;

//前台默认首页
router.get('/', (req, res) => {
    res.render('./home/index.html', {})
});


//获取上一页下一页信息
const getPage = async (target) => {
    let pagePrev = await article.findOne().where('addTime').lt(target.addTime).limit(1).exec();
    let pageNext = await article.findOne().where('addTime').gt(target.addTime).limit(1).exec();
    let page = {
        next: '',
        prev: ''
    };
    if (pagePrev) {
        page.prev = {
            title: pagePrev.title,
            url: '/article/' + pagePrev.seo.url + '.html'
        }
    }
    if (pageNext) {
        page.next = {
            title: pageNext.title,
            url: '/article/' + pageNext.seo.url + '.html'
        };
    }
    return page
};


//前台文章详情
router.get('/article/:id.html', (req, res) => {
    articleDetail(req).then(result => {
        if (result.status) {
            getPage(result.detail).then(page=>{
                res.render('home/single-post.html', {
                    data: result.detail,
                    page: page
                })
            });
        }else{
            res.send('没有找到这篇文章');
        }
    });
});

const articleDetail = async (req) => {
    let id = req.params.id;
    let routeResult = await Routes.findOne({url: id});
    if (routeResult) {
        let detail = await article.findOne({_id: routeResult.targetId});
        return {
            status: true,
            detail: detail
        }
    } else {
        let detail = await article.findOne({_id: id});
        if (detail) {
            return {
                status: true,
                detail: detail
            }
        } else {
            return {
                status: false
            }
        }
    }

};


//文章详情
router.get('/blog-lts.html', function (req, res) {
    //页码
    let page = req.params.page || 1;
    //每页数量
    let pageNum = 12;
    user.find({}, function (err, data) {
        article.count({}, function (err, counts) {
            //总页数
            let PageTotal = (Math.ceil(counts / pageNum));

            if (page > PageTotal) {
                res.redirect('/index/' + PageTotal);
                return;
            }
            article.find({}).limit(pageNum).skip((page - 1) * pageNum).exec((err, data2) => {
                if (!err) {
                    res.render('./home/blogpage.html', {
                        data: data2
                    })
                }
            })
        });

    });
});

//xx
router.get('/contact.html', function (req, res) {
    res.render('./home/contact.html')
});


//分类列表
router.get('/list/:url',(req,res)=>{
    getArticleList(req).then(result=>{
        if(result.status)
        {
            res.render('/blog-lts.html',{
                data:result.data
            })
        }else{
            res.json({
                status:false,
                msg:'没找到这个分类'
            })
        }
    });

});

const getArticleList=async(req)=>{
    let url=req.params.url;
    let target=await Routes.findOne({url:url});
    if(!target)
    {
        return{
            status:false
        }
    }
    else{
        let pageList=await article.find({cateid:target.targetId});
        return {
            status:true,
            data:pageList
        }
    }

};



//系统信息
router.get('/vue/systeminfo', (req, res) => {
    res.json({
        cpu: os.cpus(),
        arch: os.arch(),
        totalMemory: os.totalmem(),
        freeMemory: os.freemem(),
        loadavg: os.loadavg(),
        platform: os.platform(),
        release: os.release()
    })
});
module.exports = router;
